#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define sz(x) int(x.size())

typedef long long ll;
typedef pair<int, int> pii;
const int N = 1e3 + 10;
string s[N];

int ans1 = -1, ans2 = -1, ans3 = -1;
int r[4] = {0, -1, 0, 1}, c[4] = {1, 0, -1, 0};
queue<pii> q;
queue<int> qa;
bool s1[N][N], s2[N][N], s3[N][N];

void bfs1(int i, int j, int a)
{
	if(ans1 != -1) return;
	if(s1[i][j]) return;
	s1[i][j] = true;
	
	for(int k = 0; k < 4; k ++ )
	{
		if(s[i + r[k]][j + c[k]] == '.' || s[i + r[k]][j + c[k]] == 'S')
		{
			q.push({i + r[k], j + c[k]});
			qa.push(a + 1);
		}
		else if(s[i + r[k]][j + c[k]] == 'K')
		{
			ans1 = a + 1;
		}
	}
}

void bfs2(int i, int j, int a)
{
	if(ans2 != -1) return;
	if(s2[i][j]) return;
	s2[i][j] = true;
	
	for(int k = 0; k < 4; k ++ )
	{
		if(s[i + r[k]][j + c[k]] == '.' || s[i + r[k]][j + c[k]] == 'S')
		{
			q.push({i + r[k], j + c[k]});
			qa.push(a + 1);
		}
		else if(s[i + r[k]][j + c[k]] == 'K' || s[i + r[k]][j + c[k]] == 'D')
		{
			q.push({i + r[k], j + c[k]});
			qa.push(a + 1);
		}
		else if(s[i + r[k]][j + c[k]] == 'E')
		{
			ans2 = a + 1;
		}
	}
}

void bfs3(int i, int j, int a)
{
	if(ans3 != -1) return;
	if(s3[i][j]) return;
	s3[i][j] = true;
	
	for(int k = 0; k < 4; k ++ )
	{
		if(s[i + r[k]][j + c[k]] == '.' || s[i + r[k]][j + c[k]] == 'K')
		{
			q.push({i + r[k], j + c[k]});
			qa.push(a + 1);
		}
		else if(s[i + r[k]][j + c[k]] == 'E')
		{
			ans3 = a + 1;
		}
	}
}

void solve()
{
	int n, m;
	cin >> n >> m;
	for(int i = 0;i < n; i ++ )
	{
		cin >> s[i];
		for(int j = 0;j < m; j ++ )
		{
			if(s[i][j] == 'S')
			{
				q.push({i, j});
				qa.push(0);
			}
		}
	}
	
	while(!q.empty())
	{
		int i = q.front().first;
		int j = q.front().second;
		int a = qa.front();
		q.pop();
		qa.pop();
		bfs1(i, j, a);
	}
	
	for(int i = 0;i < n; i ++ )
	{
		for(int j = 0;j < m; j ++ )
		{
			if(s[i][j] == 'K')
			{
				q.push({i, j});
				qa.push(0);
			}
		}
	}
	
	while(!q.empty())
	{
		int i = q.front().first;
		int j = q.front().second;
		int a = qa.front();
		q.pop();
		qa.pop();
		bfs2(i, j, a);
	}
	
	for(int i = 0;i < n; i ++ )
	{
		for(int j = 0;j < m; j ++ )
		{
			if(s[i][j] == 'S')
			{
				q.push({i, j});
				qa.push(0);
			}
		}
	}
	
	while(!q.empty())
	{
		int i = q.front().first;
		int j = q.front().second;
		int a = qa.front();
		q.pop();
		qa.pop();
		bfs3(i, j, a);
	}
	
	if(ans3 == -1 && (ans1 == -1 || ans2 == -1)) cout << -1 << endl;
	else
	{
		if(ans3 == -1) ans3 = 10000000;
		if(ans1 == -1 || ans2 == -1) ans1 = 10000000; 
		cout << min(ans3, ans1 + ans2) << endl;
	}
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	int t = 1;
	//cin >> t;
	while(t -- ) solve();
	return 0;
}

